package com.zhiche.lisa.lspm.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.lspm.dao.model.sys.Permission;
import com.zhiche.lisa.lspm.dao.model.sys.Role;
import com.zhiche.lisa.lspm.service.sys.IRoleService;
import com.zhiche.lisa.lspm.vo.sys.RolePermRequestVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 角色 接口
 *
 * @author hxh
 * @since 2018-09-28
 */
@RestController
@RequestMapping("/role")
@Api(value = "/role", description = "角色接口", tags = {"角色接口"})
public class RoleController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CarrierController.class);

    @Autowired
    private IRoleService roleService;

    /**
     * 新建角色
     */
    @PostMapping(value = "/create", consumes = "application/json")
    public RestfulResponse<Role> createRole(@RequestBody Role role, BindingResult bindingResult) {
        RestfulResponse<Role> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        //参数校验
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            result.setCode(-1);
            StringBuilder stringBuilder = new StringBuilder();
            for (ObjectError error : errors) {
                stringBuilder.append(error.getDefaultMessage());
            }
            result.setMessage(stringBuilder.toString());
            result.setCode(-1);
            return result;
        }
        //业务处理
        try {
            //            User user = getUser();
//            User user = userService.selectById(1);
            if (roleService.insert(role)) {
                result.setData(role);
            }

        } catch (Exception e) {
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/update", consumes = "application/json")
    public RestfulResponse<Integer> updateRole(@RequestBody Role role) {
        RestfulResponse<Integer> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            if (roleService.updateById(role)) {
                result.setData(1);
            }
        } catch (Exception e) {
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/delete", consumes = "application/json")
    public RestfulResponse<Integer> deleteRole(@RequestBody List<Integer> ids) {
        RestfulResponse<Integer> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            if (roleService.deleteRole(ids)) {
                result.setData(1);
            }
        } catch (Exception e) {
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/queryRolePage")
    @ApiOperation(value = "获取角色列表", notes = "获取角色列表",
            produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Page<Role>> queryRolePage(@RequestBody Page<Role> page) {
        LOGGER.info("RoleController.queryRolePage（获取角色列表） params : {} ", page);

        RestfulResponse<Page<Role>> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);

        try {
            Page<Role> pageVo = roleService.queryRolePage(page);
            result.setData(pageVo);
        } catch (BaseException e) {
            LOGGER.error("RoleController.queryRolePage ERROR {}", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("RoleController.queryRolePage ERROR {}", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }

        return result;
    }

    @GetMapping(value = "/permission/ownBottomPermission")
    public RestfulResponse<List<Integer>> getOwnBottomPermissionIds(@RequestParam("roleId") Integer roleId) {
        RestfulResponse<List<Integer>> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {

            List<Permission> bottomPermission = roleService.getOwnBottomPermission(roleId);

            if (!Objects.equals(bottomPermission, null)) {
                List<Integer> bottomPermissionIds = new ArrayList<>();
                for (Permission permission : bottomPermission) {
                    bottomPermissionIds.add(permission.getOrders());
                }
                result.setData(bottomPermissionIds);
            }
        } catch (Exception e) {
            LOGGER.error("RoleController.getOwnBottomPermissionIds ERROR {}", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/permission/update", consumes = "application/json")
    public RestfulResponse<Integer> updateRolePermission(@RequestBody RolePermRequestVO reVO) {
        RestfulResponse<Integer> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            int i = roleService.assignPermission(reVO.getRoleId(), reVO.getPermissionIds());
            result.setData(i);
        } catch (Exception e) {
            LOGGER.error("RoleController.updateRolePermission ERROR {}", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

}

